<?php

namespace app\madmin\service;

use think\Exception;
use think\facade\Db;
use app\madmin\model\Presell;
use app\madmin\model\PresellCommodity;

class PresellService
{

    private function buildWhere(array $data)
    {
        $where = [];
        !empty($data['status']) && $where[] = ['status', 'in', $data['status']];
        return $where;
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function index($page = 1, $size = 10, $search = [])
    {
        $list = Presell::where($this->buildWhere($search))->order('status ASC')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws
     */
    public function save(array $data)
    {
        $check = Presell::check($data);
        try {
            Db::startTrans();
            $group = Presell::create($check['group']);
            foreach ($check['commodity'] as $key => $value) {
                $commodity = $group->commodity()->save($value);
                if ($value['has_sku'] == 1) {
                    $commodity->sku()->saveAll($value['skus']);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $group];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = Presell::with(['commodity' => function ($sql) {
            $sql->with(['goods', 'sku' => function ($query) {
                $query->with('sku');
            }]);
        }])->find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws
     */
    public function update(int $id, array $data)
    {
        try {
            Db::startTrans();
            $rules = json_decode(Presell::find($id)['rules'], true);
            $update = [
                'rules' => json_encode($rules),
                'end_time' => $data['end_time']
            ];
            $goods_update = [
                'end_time' => $data['end_time']
            ];
            // 过期
            if ($data['end_time'] < date("Y-m-d H:i:s", time())) {
                $update['status'] = 2;
                $goods_update['status'] = 2;
            }
            Presell::update($update, ['id' => $id]);
            PresellCommodity::update($goods_update, ['presell_id' => $id]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("发生错误！", HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, "更新成功！"];
    }

    /**
     * @param $id
     * @return array
     * @throws
     */
    public function stop($id)
    {
        try {
            Presell::update([
                'close_time' => date('Y-m-d H:i:s', time()),
                'status' => 2
            ], ['id' => $id]);
            $res = PresellCommodity::update(['status' => 2], ['presell_id' => $id]);
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("发生错误！", HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $res];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        Presell::update(['status' => 2], ['id' => $id]);
        PresellCommodity::update(['status' => 2], ['presell_id' => $id]);
        Presell::destroy($id);
        return HTTP_NOCONTEND;
    }

}
